import {Sequelize, Op} from 'sequelize';
import _ from 'lodash';
import BaseBusinessController from './../base/BaseBusinessController'


class PermissionController extends BaseBusinessController {


    async actionGetBuildings(){
        let buildingIds = await super.buildingIds(this.state.user.id);

        P(buildingIds)


        return buildingIds;

    }


    /**
     * 获取某端的权限ID
     * @returns {Promise<void>}
     */
    async actionApp(){
        let appId = $_POST['app_id']
        if(!appId){
            throw new Error('请确认端')
        }

        let sql = `select p.* from hz_app_permission ap
        INNER JOIN hz_permission p ON p.id = ap.permission_id 
        where ap.app_id = ${appId}`

        let permissions = await db.sql(sql);
        /**
         * 树结构遍历重组
         * @type {Array}
         */
        return this._parsePermissionTree(permissions);

    }


    /**
     * 获取该账号下可以分配的所有权限
     * @returns {Promise<void>}
     */
    async actionAccountPermission(){
        let account = await super.findAccount(this.state)

        if(!account['app_id'] || !account['role_id']){
            throw new Error("账号数据错误")
        }

        let role = await this.modules('Role').where({id: account.role_id}).first()
        if (!role) {
            throw new Error("角色查询失败,请联系管理员")
        }

        let sql;
        /**
         * 1.端超管- 获取该端下所有的权限列表
         * 2.端非超管，获取的是该角色的权限列表
         */
        if(role['is_admin'] === 1){
            sql = `select p.* from hz_app_permission ap
            INNER JOIN hz_permission p ON p.id = ap.permission_id 
            where ap.app_id = ${account['app_id']}`
        }else{
            sql = `select p.* from hz_role_permission rp
            INNER JOIN hz_permission p ON p.id = rp.permission_id 
            where rp.role_id = ${account['role_id']}`
        }

        let permissions = await db.sql(sql);
        /**
         * 树结构遍历重组
         * @type {Array}
         */
        return this._parsePermissionTree(permissions);
    }


    /**
     * 查询
     * @return {[type]} [description]
     */
    async actionFind() {
        super._validatePostId($_POST)
        let id = $_POST['id'];
        return await super._findPermission(id);
    }

    /**
     * 查询所有权限列表
     * @return {[type]} [description]
     */
    async actionFindAll(){
        let {number, size} = this._getPage()
        return await this.modules('Permission').page(number, size).select();
    }


    /**
     * 权限树
     * @returns {Promise<*>}
     */
    async actionTree(){
        let permissions = await this.modules("Permission").select(false, {raw: true});

        /**
         * 树结构遍历重组
         * @type {Array}
         */
        return this._parsePermissionTree(permissions);
    }

    /**
     * 新增
     * @return {[type]} [description]
     */
    async actionAdd() {
        let {name, pid, type} = $_POST;
        if(!name || !type){
            throw new Error("参数缺失")
        }

        let data = await this.modules('Permission').insert($_POST);
        if (data) {
            return data;
        } else {
            throw new Error('保存失败');
        }
    }

    /**
     * 编辑
     * @return {[type]} [description]
     */
    async actionUpdate() {
        let {id, name, pid, code} = $_POST;

        if(!id){
            throw new Error("ID参数缺失")
        }

        let data = await this.modules('Permission').where({ id }).update({name, pid, code});
        if (data) {
            return data;
        } else {
            throw new Error('保存失败');
        }
    }


    /**
     * 删除
     * @returns {Promise.<boolean>}
     */
    async actionDelete() {
        let id = $_POST['id'];
        if(!id){
            throw new Error("ID参数缺失")
        }

       let permission = await this.modules('Permission').where({ id }).first();

        if(!permission){
            throw new Error("权限已不存在")
        }

        let ids = await this._getSubPermissionIds(permission);

        let t = await db.transaction();
        try{
            let where = {id: {[Op.in]: ids}}
            await this.modules('Permission').where(where).destroy({transaction: t});
            let rolePermissionWhere = {permission_id: {[Op.in]: ids}}
            await this.modules('Role.RolePermission').where(rolePermissionWhere).destroy({transaction: t});
            await t.commit();
            return true;
        } catch (error) {
            await t.rollback();
            throw new Error("update failure");
        }
    }

}

export default PermissionController;
